package PacketTools;

import java.io.*;
import java.net.DatagramPacket;
import java.net.InetAddress;

/**
 *
 * @author Jakub Banaszewski
 */
public class PacketRequest implements Serializable
{

   private short session;
   private short packetNumber;
   public static int MAXPACKETSIZE = 128;

   public PacketRequest()
   {
   }

   public byte[] packetToByte() throws IOException
   {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(bos);
      oos.writeObject(this);
      oos.flush();
      oos.close();
      bos.close();
      byte[] data = bos.toByteArray();
      if (data.length > MAXPACKETSIZE)
         throw new IOException("Unusual serialization. Expected : " + MAXPACKETSIZE + ". Get: " + data.length);
      return data;
   }

   public static PacketRequest byteToPacket(byte[] bytes) throws IOException, ClassNotFoundException
   {
      PacketRequest ans;
      try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)))
      {
         ans = (PacketRequest) in.readObject();
      }
      return ans;
   }

   public void setSession(short sessionNumber)
   {
      session = sessionNumber;
   }

   public short getSession()
   {
      return session;
   }

   public short getPacketNumber()
   {
      return packetNumber;
   }

   public void setPacketNumber(short packetNumber)
   {
      this.packetNumber = packetNumber;
   }

   public DatagramPacket makeDatagram(InetAddress address, int port) throws IOException
   {
      byte[] buf = packetToByte();
      return new DatagramPacket(buf, buf.length, address, port);
   }
}